package com.example.wlzz.aspect;
import com.example.wlzz.constant.RedisConstant;
import com.example.wlzz.enums.ResultEnum;
import com.example.wlzz.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by yhn on 2018/5/17.
 */
@Aspect
@Component
@Slf4j
@Order(value = 1)
public class UserAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Around("execution(* com.example.wlzz.controller.*.*(..))&&" +
            "!execution(* com.example.wlzz.controller.UserController.*(..))&&"+
            "!execution(* com.example.wlzz.controller.SystemController.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp)throws Throwable{
          ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
          HttpServletRequest request = attributes.getRequest();
          String token = request.getParameter("token");
        //去redis查询
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.LOGIN_SUCCESS_TOKEN, token));
        if (StringUtils.isEmpty(tokenValue)) {  //查询redis
            log.error("【切面登陆校验】Redis中查不到token");
            return ResultVOUtil.error(ResultEnum.NO_LOGIN.getCode(),ResultEnum.NO_LOGIN.getMessage());
        }
          Object object = pjp.proceed();  //拿到方法返回值的对象
          return object;
    }
}